import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { message, Table, Button, Popconfirm, Space, Tag } from 'antd';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import React, { useRef, useState } from 'react';
import { useIntl, useRequest } from 'umi';
import styles from './index.less';
import {
    postApiCrontabByIndexByLimitPagedList as PagedList,
    getApiCrontabDetailById as Detail,
    deleteApiCrontab as Delete,
    getApiCrontabDefinitions as JobDerinitions,
    getApiCrontabByIdStart as Start,
    getApiCrontabByIdStop as Stop
} from '@/services/furion-cms/crontab';
import CrontabDetail from './components/detail';
import CrontabExecuteRecord from './components/executeRecord';
import PermissionsDefinition from '@/permissionsDefinition';
import { useCustomAccess } from '@/components/CustomAccess';

const CrontabManager: React.FC = () => {
    const actionRef = useRef<ActionType>();
    /**
     * @en-US International configuration
     * @zh-CN 国际化配置
     * */
    const intl = useIntl();
    const [loadingVisible, handelLoadingVisible] = useState(false);
    const [details, setDetails] = useState<API.CrontabDetailDto>();
    const [detailModalVisible, handleDetailModalVisible] = useState(false);
    const [recordModalVisible, handleRecordModalVisible] = useState(false);

    const { data: jobInstances, loading } = useRequest(JobDerinitions, {
        loadingDelay: 500
    });

    const AccessButton = useCustomAccess(Button);
    const AccessConfirm = useCustomAccess(Popconfirm);

    const jobInstanceDic = {};
    if (!loading) {
        jobInstances?.forEach(f => {
            jobInstanceDic[f.value] = f.label;
        })
    }

    const handleStatusSwitch = async (row: API.CrontabDto) => {
        try {
            switch (row.status?.value) {
                case 0:
                    // 停止
                    await Stop({ id: row.id! });
                    break;
                case 1:
                case 2:
                case 3:
                    //运行
                    await Start({ id: row.id! });
                    break;
            }
            message.success('状态切换成功');
            actionRef.current?.reload();
        } catch { }
    }

    const detailHandle = async (id: string) => {
        handelLoadingVisible(true);
        try {
            const { data } = await Detail({ id });
            setDetails(data);
            handleDetailModalVisible(true);
        } catch { }
        handelLoadingVisible(false);
    }

    const recordHandle = async (record: API.CrontabDto) => {
        setDetails(record);
        handleRecordModalVisible(true);
    }
    const handleDelete = async (idList: string[]) => {
        handelLoadingVisible(true);
        try {
            await Delete(idList);
            message.success('任务删除成功');
            actionRef.current?.reload();
        } catch { }
        handelLoadingVisible(false);
    }

    const columns: ProColumns<API.CrontabDto>[] = [
        {
            title: intl.formatMessage({
                id: 'pages.crontab.table.instancePath',
                defaultMessage: '任务实例'
            }),
            dataIndex: 'instancePath',
            search: false,
            render: (_, entity) => jobInstanceDic[entity.instancePath!] ?? '未知'
        },
        {
            title: intl.formatMessage({
                id: 'pages.crontab.table.description',
                defaultMessage: '任务描述'
            }),
            dataIndex: 'description',
            search: false,
        },
        {
            title: intl.formatMessage({
                id: 'pages.crontab.table.enable',
                defaultMessage: '是否启用'
            }),
            dataIndex: 'enable',
            width: 120,
            search: false,
            render: (_, entity) => {
                if (entity.enable) {
                    return <Tag color="success">启用</Tag>
                }
                return <Tag color="error">禁用</Tag>
            }
        },
        {
            title: intl.formatMessage({
                id: 'pages.crontab.table.status',
                defaultMessage: '状态'
            }),
            dataIndex: ['status', 'code'],
            search: false,
            width: 100,
            valueEnum: {
                Running: { text: '运行中', status: 'Processing' },
                Stopped: { text: '已停止', status: 'Default' },
                Failed: { text: '执行失败', status: 'Error' },
                CanceledOrNone: { text: '未激活', status: 'Warning' },
            }
        },
        {
            title: intl.formatMessage({
                id: 'pages.crontab.table.createdTime',
                defaultMessage: '创建时间'
            }),
            dataIndex: 'createdTime',
            valueType: 'dateRange',
            sorter: true,
            width: 180,
            render: (dom, entity) => {
                return entity.createdTime;
            }
        },
        {
            title: intl.formatMessage({
                id: 'pages.searchTable.titleOption',
                defaultMessage: '操作'
            }),
            dataIndex: 'option',
            valueType: 'option',
            width: 250,
            render: (_, record) => [
                <AccessButton key="update"
                    code={PermissionsDefinition.Crontab.UpdateCrontab}
                    type="link" size="small"
                    onClick={() => detailHandle(record.id!)}>
                    {intl.formatMessage({
                        id: 'pages.common.update',
                        defaultMessage: '编辑'
                    })}
                </AccessButton>,
                <AccessConfirm key="switch"
                    code={PermissionsDefinition.Crontab.SwitchCrontabState}
                    title={intl.formatMessage({
                        id: 'pages.common.switch.confirm',
                        defaultMessage: '您是否确认{status}「{name}」?'
                    }, {
                        name: jobInstanceDic[record.instancePath!],
                        status: record.status?.value === 0 ? '注销' : '激活'
                    })}
                    onConfirm={() => handleStatusSwitch(record)}
                >
                    <Button type="link" size="small"
                    >{intl.formatMessage({
                        id: 'pages.common.switch',
                        defaultMessage: '切换'
                    })}</Button>
                </AccessConfirm>,
                <Button key="record" type="link" size="small"
                    onClick={() => recordHandle(record)}>
                    {intl.formatMessage({
                        id: 'pages.common.record',
                        defaultMessage: '记录'
                    })}</Button>,
                <AccessConfirm key="delete" code={PermissionsDefinition.Crontab.DeleteCrontab}
                    title={<Space direction="vertical">
                        {intl.formatMessage({
                            id: 'pages.common.delete.confirm',
                            defaultMessage: '您是否确认将「{name}」删除?'
                        }, {
                            name: jobInstanceDic[record.instancePath!]
                        })}
                        {record.description}
                    </Space>}
                    onConfirm={() => handleDelete([record.id!])}
                >
                    <Button type="link" size="small">
                        {intl.formatMessage({
                            id: 'pages.common.delete',
                            defaultMessage: '删除'
                        })}
                    </Button>
                </AccessConfirm>
            ]
        }
    ]

    return (<PageContainer
        className={styles.main}
        loading={loading}
        breadcrumbRender={false}>
        <ProTable<API.CrontabDto>
            rowKey="id"
            loading={loadingVisible}
            actionRef={actionRef}
            search={{ filterType: "light" }}
            pagination={{
                pageSize: 10,
                showSizeChanger: true
            }}
            rowSelection={{
                selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
            }}
            toolBarRender={() => [
                <AccessButton key="create"
                    code={PermissionsDefinition.Crontab.CreateCrontab}
                    type="primary"
                    onClick={() => {
                        setDetails(undefined);
                        handleDetailModalVisible(true);
                    }}>
                    {intl.formatMessage({
                        id: 'pages.crontab.create',
                        defaultMessage: '创建任务'
                    })}
                </AccessButton>,
            ]}
            columns={columns}
            request={(params, sort, filter) => {
                // 表单搜索项会从 params 传入，传递给后端接口。
                console.log(params, sort, filter);
                handelLoadingVisible(true);
                // 转换固定的参数
                const { current, pageSize, createTime } = params;
                const [StartTime, EndTime] = createTime || [];
                // 删除无效参数
                delete params.current;
                delete params.pageSize;
                delete params.createTime;
                return PagedList({
                    index: (current || 1),
                    limit: (pageSize || 10),
                    StartTime,
                    EndTime,
                    ...params
                }, sort).then(result => {
                    const { list: data, total } = result.data || {};
                    return {
                        data,
                        success: result.success,
                        total
                    }
                }).finally(() => handelLoadingVisible(false));
            }}
        />
        <CrontabDetail
            modalVisible={detailModalVisible}
            onVisibleChange={handleDetailModalVisible}
            recored={details}
            jobInstances={jobInstances}
            onUpdate={() => {
                actionRef.current?.reload();
                setDetails(undefined);
                handleDetailModalVisible(false);
            }}
        />
        <CrontabExecuteRecord
            recored={details}
            jobInstanceDic={jobInstanceDic}
            visible={recordModalVisible}
            onVisibleChange={handleRecordModalVisible}
        />
    </PageContainer>)
}

export default CrontabManager;